package ldh.maker.db;

import ldh.database.Table;
import ldh.maker.freemaker.EnumStatusMaker;
import ldh.maker.util.CommonUtil;
import ldh.maker.util.EnumFactory;
import ldh.maker.util.UiUtil;
import ldh.maker.vo.EnumData;
import ldh.maker.vo.SettingData;
import ldh.maker.vo.TreeNode;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by ldh on 2017/4/19.
 */
public class EnumDb {

    public static void loadData(int treeNodeId, String dbName) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        String sql = "select * from pojo_enum where tree_node_id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, treeNodeId);
        ResultSet rs = statement.executeQuery();
        while(rs.next()){
            EnumStatusMaker data = new EnumStatusMaker();
            data.pack(rs.getString("pack")).name(rs.getString("name"))
                .choiceType(rs.getString("type"))
                .columnName(rs.getString("column_name"))
                .tableName(rs.getString("tableName"));
            String value = rs.getString("text");
            String[] values = value.split("\\|");
            for (String v : values) {
                Object o = CommonUtil.to(CommonUtil.getValue(v), data.getChoiceType());
                EnumData ed = new EnumData(o, CommonUtil.getDesc(v));
                data.addValue(CommonUtil.getName(v), ed).type(o.getClass());
            }
            Class clazz = CommonUtil.to(CommonUtil.getValue(value), data.getChoiceType()).getClass();
            data.type(clazz).columnName(data.getColumnName()).tableName(data.getTableName());
            String key = treeNodeId + "_" + dbName + "_" + data.getTableName() + "_" + data.getColumnName();
            EnumFactory.getInstance().put(key, data);
        }
        statement.close();
    }

    public static void save(int treeNodeId) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        String sql = "insert into pojo_enum(pack, name, type, text, column_name, tableName, tree_node_id) values(?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        for (EnumStatusMaker esm : EnumFactory.getInstance().getEnumStatusMakerMap().values()) {
            statement.setString(1, esm.getPack());
            statement.setString(2, esm.getClassName());
            statement.setString(3, esm.getChoiceType());
            statement.setString(5, esm.getColumnName());
            statement.setString(6, esm.getTableName());
            statement.setInt(7, treeNodeId);
            Map<String, EnumData> values = esm.getValues();
            StringBuilder sb = new StringBuilder();
            boolean isFirst = true;
            for (Map.Entry<String, EnumData> entry : values.entrySet()) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    sb.append("|");
                }
                sb.append(entry.getKey());
                if (entry.getValue() != null) {
                    sb.append("(").append(entry.getValue().getValue().toString()).append(")" + "--" + entry.getValue().getDesc());
                }
            }
            statement.setString(4, sb.toString());
            statement.addBatch();
        }
        statement.executeBatch();
        statement.close();
    }

    public static void update(int treeNodeId) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        String sql = "delete pojo_enum  where tree_node_id=?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, treeNodeId);
        statement.executeUpdate();
        statement.close();

        save(treeNodeId);
    }

    public static List<Object> getValues(Connection connection, String tableName, String column) throws SQLException {
        List<Object> result = new ArrayList();
        String sql = String.format("select distinct %s from %s limit 100", column, tableName);
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet rs = statement.executeQuery();
        while(rs.next()){
            result.add(rs.getObject(1));
        }
        statement.close();
        return result;
    }

    public static void delete(TreeNode treeNode) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        QueryRunner queryRunner = new QueryRunner();
        String sql = "delete from pojo_enum where tree_node_id = ?";
        queryRunner.update(connection, sql, treeNode.getId());
    }
}
